import requests
import time
import random
import re
import json
import signal
import sys
from urllib.parse import urljoin
from bs4 import BeautifulSoup

# 全局变量，用于控制程序退出
interrupted = False


def signal_handler(sig, frame):
    """处理中断信号"""
    global interrupted
    print(f"\n\n收到中断信号，正在优雅退出...")
    interrupted = True
    sys.exit(0)


def claim_daily_reward(session):
    """
    自动领取昨日活跃度奖励

    Args:
        session: requests Session对象

    Returns:
        dict: 领取结果
    """
    # 检查是否被中断
    if interrupted:
        return {'success': False, 'message': '程序已中断', 'data': None}

    # API地址
    url = "https://fishpi.cn/activity/yesterday-liveness-reward-api"

    # 添加时间戳参数
    timestamp = int(time.time() * 1000)
    full_url = f"{url}?_={timestamp}"

    try:
        # 发送GET请求
        response = session.get(full_url, timeout=10)
        response.raise_for_status()

        # 解析响应
        result = response.json()

        # 根据响应判断领取结果
        sum_value = result.get('sum')

        if sum_value == 100:
            return {
                'success': True,
                'message': '奖励领取成功！获得100积分',
                'data': result
            }
        elif sum_value == -1:
            return {
                'success': False,
                'message': '今日已领取过奖励',
                'data': result
            }
        elif sum_value > 0:
            return {
                'success': True,
                'message': f'奖励领取成功！获得{sum_value}积分',
                'data': result
            }
        else:
            return {
                'success': False,
                'message': f'未知响应: {result}',
                'data': result
            }

    except requests.exceptions.RequestException as e:
        return {
            'success': False,
            'message': f'网络请求失败: {str(e)}',
            'data': None
        }
    except json.JSONDecodeError as e:
        return {
            'success': False,
            'message': f'响应解析失败: {str(e)}',
            'data': None
        }


def safe_sleep(seconds):
    """安全的睡眠函数，支持中断"""
    end_time = time.time() + seconds
    while time.time() < end_time and not interrupted:
        remaining = end_time - time.time()
        if remaining > 0.5:
            time.sleep(min(0.5, remaining))
        else:
            time.sleep(remaining)
            break


def random_visit_recent_articles():
    # 配置信息
    COOKIE = ''
    TOTAL_VISITS = 25

    session = requests.Session()
    session.headers.update({
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
        'Cookie': COOKIE,
        'Accept': 'application/json, text/javascript, */*; q=0.01',
        'X-Requested-With': 'XMLHttpRequest',
        'Referer': 'https://fishpi.cn/activity'
    })

    base_url = "https://fishpi.cn"
    recent_url = "https://fishpi.cn/recent"

    def get_article_links():
        if interrupted:
            return []
        try:
            response = session.get(recent_url, timeout=10)
            if response.status_code == 200:
                soup = BeautifulSoup(response.content, 'html.parser')
                links = []

                for a in soup.find_all('a', href=re.compile(r'/article/\d+')):
                    href = a.get('href')
                    if href:
                        full_url = urljoin(base_url, href)
                        if full_url not in links:
                            links.append(full_url)

                return links[:20]  # 返回前20篇文章
            return []
        except:
            return []

    # 注册中断信号处理
    signal.signal(signal.SIGINT, signal_handler)

    print("=" * 50)
    print("开始执行FishPi自动化任务")
    print("提示: 按 Ctrl+C 可随时中断程序")
    print("=" * 50)

    # 第一步：尝试领取奖励
    print("\n1. 尝试领取每日奖励...")
    reward_result = claim_daily_reward(session)
    print(f" 奖励领取结果: {reward_result['message']}")


    if reward_result['success']:
        sum_value = reward_result['data'].get('sum', 0)
        print(f" 成功获得 {sum_value} 积分！")


    if interrupted:
        print("\n程序被中断")
        return


    print(f"\n2. 开始随机访问最新文章 {TOTAL_VISITS} 次")
    print("-" * 40)

    success_count = 0

    for i in range(TOTAL_VISITS):

        if interrupted:
            print(f"\n程序被中断，已完成 {success_count} 次访问")
            break

        try:

            if i % 5 == 0:
                articles = get_article_links()
                if not articles:
                    print("   无法获取文章列表")
                    safe_sleep(10)
                    continue
                print(f"   获取到 {len(articles)} 篇文章")

            # 随机选择一篇文章
            article_url = random.choice(articles)

            response = session.get(article_url, timeout=10)

            if response.status_code == 200:
                success_count += 1
                print(f"   第 {i + 1:2d} 次访问成功")
            else:
                print(f"   第 {i + 1:2d} 次访问失败: {response.status_code}")

            # 随机延迟（使用安全的睡眠函数）
            if i < TOTAL_VISITS - 1 and not interrupted:
                delay = random.uniform(3, 8)
                safe_sleep(delay)

        except Exception as e:
            if not interrupted:  # 如果不是因为中断导致的异常
                print(f"   第 {i + 1:2d} 次访问异常: {e}")
            continue

    print(f"\n3. 任务完成!")
    print("=" * 50)
    print(f"   奖励领取: {reward_result['message']}")
    print(f"   文章访问: 成功 {success_count}/{TOTAL_VISITS} 次")
    print("=" * 50)


if __name__ == "__main__":
    try:
        random_visit_recent_articles()
    except KeyboardInterrupt:
        print("\n程序被用户中断")
    except Exception as e:
        print(f"\n程序发生错误: {e}")
